package com.birdboot.core;

import java.io.IOException;
import java.io.InputStream;
import java.net.Socket;

/**
 * 该线程任务负责与指定客户端进行一次HTTP交互
 *
 * 1:解析请求
 * 2:处理请求
 * 3:回复响应
 *
 */
public class ClientHandler implements Runnable{
    private Socket socket;
    public ClientHandler(Socket socket){
        this.socket = socket;
    }
    public void run() {
        try {
            //1解析请求
            InputStream in = socket.getInputStream();
            int d;

            StringBuilder builder = new StringBuilder();
            //pre:表示上次读取的字符,cur表示本次读取的字符
            char pre='a',cur='a';
            while( (d = in.read()) != -1    ){
                cur = (char)d;//本次读取的字符
                //是否连续读取到了回车+换行
                if(pre==13 && cur==10){
                    break;//停止读取,一行已经读取完毕了
                }
                builder.append(cur);//将本次读取的字符拼接
                pre = cur;//在下次读取前,将本次读取的字符记作上次读取的字符
            }
            String line = builder.toString().trim();
            System.out.println(line);
            //请求行相关信息
            String method;
            String uri;
            String protocol;
            //[GET, /index.html, HTTP/1.1]
            String[] data = line.split("\\s");
            method = data[0];
            uri = data[1];
            protocol = data[2];
            System.out.println("method:"+method);//method:GET
            System.out.println("method:"+uri);//uri:/index.html
            System.out.println("method:"+protocol);//protocol:HTTP/1.1





        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

